<template>
  <div class="dropdown" ref="dropdownRef">
    <a
      href="#"
      class="btn btn-outline-light my-2"
      @click.prevent="toggleOpen"
      >{{ title }}</a>
    <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isOpen">
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref,  watch } from "vue";
import useClickOutside from '../hooks/useClickOutside'
export default defineComponent({
  name: "DropDown",
  props: {
    title: {
      type: String,
      required: true,
    },
  },
  setup() {
    // 点击显示和隐藏 DropDown
    const isOpen = ref(false);
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    };

    const dropdownRef = ref<null | HTMLElement>(null)
    // const handler = (e: MouseEvent) => {
    //     if(dropdownRef.value) {
    //         console.log(dropdownRef.value.contains(e.target as HTMLElement));
    //         console.log(isOpen.value)
    //         if(!dropdownRef.value.contains(e.target as HTMLElement) && isOpen.value) {
    //             isOpen.value = false
    //         }
    //     }
    // }
    // onMounted(() => {
    //     document.addEventListener('click', handler)
    // })
    // onUnmounted(() => {
    //     document.removeEventListener('click', handler)
    // })
    const isClickOutSide = useClickOutside(dropdownRef)
    
    watch(isClickOutSide, () => {
        if(isOpen.value && isClickOutSide.value) {
            isOpen.value = false
        }
    })

    return {
      isOpen,
      toggleOpen,
      dropdownRef
    };
  },
});
</script>

<style></style>
